<template>
  <div class="login-container">
    <div class="login-box">
      <h2>用户登录</h2>
      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="form.username"
            placeholder="请输入用户名"
          />
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="form.password"
            placeholder="请输入密码"
          />
        </div>

        <div class="form-group captcha-group">
          <label for="captcha">验证码</label>
          <div class="captcha-input-container">
            <input
              type="text"
              id="captcha"
              v-model="form.captcha"
              placeholder="请输入验证码"
              class="captcha-input"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaImage" alt="验证码" v-if="captchaImage" />
              <span v-else>加载验证码...</span>
            </div>
          </div>
        </div>

        <div class="remember-me">
          <input type="checkbox" id="remember" v-model="form.remember" />
          <label for="remember">记住我</label>
        </div>

        <button type="submit" :disabled="loading">
          {{ loading ? '登录中...' : '立即登录' }}
        </button>

        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
      </form>

      <div class="additional-actions">
        <a href="#" @click.prevent="handleForgotPassword">忘记密码？</a>
        <a href="#" @click.prevent="handleRegister">立即注册</a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单数据
const form = ref({
  username: '',
  password: '',
  captcha: '',
  remember: false
})

// 验证码相关
const captchaImage = ref('')
const captchaToken = ref('')

// 状态管理
const loading = ref(false)
const errorMessage = ref('')

// 生成随机字符串用于验证码
const generateRandomString = (length = 4) => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 生成验证码图片（模拟）
const generateCaptcha = () => {
  // 在实际项目中，这里应该是从后端获取验证码图片
  const randomText = generateRandomString()
  captchaToken.value = randomText // 保存验证码用于验证
  
  // 模拟生成验证码图片（实际项目中应该使用后端API）
  const canvas = document.createElement('canvas')
  canvas.width = 120
  canvas.height = 40
  const ctx = canvas.getContext('2d')
  
  // 绘制背景
  ctx.fillStyle = '#f5f5f5'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.floor(Math.random() * 150)}, ${Math.floor(Math.random() * 150)}, ${Math.floor(Math.random() * 150)})`
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }
  
  // 绘制文字
  ctx.font = '24px Arial'
  ctx.fillStyle = '#333'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillText(randomText, canvas.width / 2, canvas.height / 2)
  
  // 转换为DataURL
  captchaImage.value = canvas.toDataURL('image/png')
}

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha()
}

// 初始化验证码
onMounted(() => {
  refreshCaptcha()
})

// 表单提交处理
const handleSubmit = async () => {
  if (!form.value.username || !form.value.password) {
    errorMessage.value = '用户名和密码不能为空'
    return
  }

  if (!form.value.captcha) {
    errorMessage.value = '请输入验证码'
    return
  }

  // 验证验证码（不区分大小写）
  if (form.value.captcha.toUpperCase() !== captchaToken.value.toUpperCase()) {
    errorMessage.value = '验证码不正确'
    refreshCaptcha()
    form.value.captcha = ''
    return
  }

  try {
    loading.value = true
    errorMessage.value = ''

    // 模拟登录请求
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 登录成功后的处理
    if (form.value.remember) {
      localStorage.setItem('username', form.value.username)
    }
    
    // 跳转到首页
    router.push('/home')
  } catch (error) {
    errorMessage.value = '登录失败，请检查用户名和密码'
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 其他操作
const handleForgotPassword = () => {
  // 处理忘记密码逻辑
  console.log('忘记密码')
}

const handleRegister = () => {
  // 跳转到注册页面
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 100vw;
  min-height: 100vh;
  box-sizing: border-box;
}

.login-box {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
}

input[type="text"],
input[type="password"] {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.captcha-group {
  margin-bottom: 20px;
}

.captcha-input-container {
  display: flex;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 40px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-image:hover {
  opacity: 0.8;
}

.remember-me {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.remember-me input {
  margin-right: 8px;
}

button {
  width: 100%;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #0056b3;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.additional-actions {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.additional-actions a {
  color: #007bff;
  text-decoration: none;
  font-size: 14px;
}

.additional-actions a:hover {
  text-decoration: underline;
}

.error-message {
  color: #dc3545;
  font-size: 14px;
  margin-top: 10px;
  text-align: center;
}
</style>